package com.jmpt.fangbohui.ui.personalcenter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.BrokerInfoBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval;
import com.jmpt.fangbohui.bean.LoginBean;
import com.jmpt.fangbohui.bean.PasswordBean;
import com.jmpt.fangbohui.bean.UserInfoBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_city;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_province;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_zone;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.ui.base.BaseActivity;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ImageLoaderHelper;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;

//根据数据库当前登录的用户类型信息，从网络获取处当前要显示的内容
public class UserInfoDetailActivity extends BaseHeadActivity {
	
	@ViewInject(R.id.iv_user_info_edit_icon_real)
	private ImageView iv_user_info_edit_icon_real;
	
	@ViewInject(R.id.tv_user_info_edit_nicheng_real)
	private TextView tv_user_info_edit_nicheng_real;
	
	@ViewInject(R.id.tv_user_info_edit_sex_real)
	private TextView tv_user_info_edit_sex_real;
	
	@ViewInject(R.id.tv_user_info_edit_place_real)
	private TextView tv_user_info_edit_place_real;
	
	@ViewInject(R.id.tv_user_info_edit_province_real)
	private TextView tv_user_info_edit_province_real;
	
	@ViewInject(R.id.tv_user_info_edit_phone_real)
	private TextView tv_user_info_edit_phone_real;
	
	@ViewInject(R.id.tv_user_info_edit_email_real)
	private TextView tv_user_info_edit_email_real;
	
	
	@ViewInject(R.id.tv_user_info_edit_birthday_real)
	private TextView tv_user_info_edit_birthday_real;

	

	public final static int SUCCESS = 200;
	public final static int FAILED = 202;

	private static final int SUCCESS_CHANGEPASSWORD = 101;
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			hideLoading();
			switch(msg.what){
			case SUCCESS:
					tv_user_info_edit_email_real.setText(email);
					tv_user_info_edit_sex_real.setText(sex);
					tv_user_info_edit_birthday_real.setText(birth_y+"年"+birth_m+"月");
					for(date_city element : result.date_city){
						if(element.CityID.equals(cityid)){
							tv_user_info_edit_place_real.setText(element.CityName);
						}
					}
					for(date_province element : result.date_province){
						if(element.ProvinceID.equals(provinceid)){
							tv_user_info_edit_province_real.setText(element.ProvinceName);
						}
					}
					ImageLoaderHelper.displayImage(picUrl, iv_user_info_edit_icon_real);
				ToastHelper.ShowToast("操作成功", UserInfoDetailActivity.this);
			break;
			case FAILED:
				ToastHelper.ShowToast("操作失败", UserInfoDetailActivity.this);
			break;
			case SUCCESS_CHANGEPASSWORD:
				PasswordBean bean = (PasswordBean) msg.obj;
				ToastHelper.ShowToast(bean.msg, UserInfoDetailActivity.this);
			}
			
		};
	};

	private boolean isFirstLoad = true;
	
	private String email;

	private String birth_y;

	private String birth_m;

	private String qq;

	private String sex;

	private String zoneid;

	private String cityid;

	private String provinceid;

	private String serv_zone;

	private String oldpic;

	private String picUrl;

	private EditText et_old_password;

	private EditText et_new_password;

	private EditText et_new2_password;

	private SharedPreferences sp;

	private EntryingHouseDropDownBean dropDownBean;

	private ArrayList<String> province;

	private ArrayList<String> city;

	private ArrayList<String> provinceIds;

	private ArrayList<String> cityIds;

	private Retval result;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initSpinnerData();
	}

	private void initSpinnerData() {
		showLoading();
		sp = getSharedPreferences("config", MODE_PRIVATE);
		String cacheDropDown = sp.getString(
				Constants.SharedPreferences.CACHEDROPDOWN, null);
		if (TextUtils.isEmpty(cacheDropDown)) {
			parsersAddress(cacheDropDown);
		}
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.GET, Constants.URL.SecondaryHousingDropDown,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						hideLoading();
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						sp.edit()
								.putString(
										Constants.SharedPreferences.CACHEDROPDOWN,
										arg0.result).commit();
						parsersAddress(arg0.result);
					}
				});
	}

	protected void parsersAddress(String result) {
		hideLoading();
		DebugLog.i(result);
		Gson gson = new Gson();
		dropDownBean = gson.fromJson(result, EntryingHouseDropDownBean.class);
		// 拆分数据
		if (dropDownBean != null) {
			splitList(dropDownBean);
		}
	}
	private void splitList(EntryingHouseDropDownBean bean) {
		province = new ArrayList<String>();
		city = new ArrayList<String>();

		provinceIds = new ArrayList<String>();
		cityIds = new ArrayList<String>();

		result = bean.retval;
		for (date_province date_provinces : result.date_province) {
			province.add(date_provinces.ProvinceName);
			provinceIds.add(date_provinces.ProvinceID);
		}
		for (date_city date_citys : result.date_city) {
			city.add(date_citys.CityName);
			cityIds.add(date_citys.CityID);
		}
		init();
		isFirstLoad = false;
		initView();
		initData();
	}
	private void init() {
		LoginSQLiteOperator oper = new LoginSQLiteOperator(this);
		
		final LoginBean bean2 = oper.query();
		if(bean2 == null){
			return;
		}
			//获取用户
			new Thread(){
				public void run() {
					HttpClient httpClient = new DefaultHttpClient();
					try {
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("UserId",bean2.getRetval().getUserId()));
						params.add(new BasicNameValuePair("UserName",bean2.getRetval().getUserName()));
						
						HttpPost postMethod = new HttpPost(Constants.URL.READUSERINFO);
						postMethod.setHeader("Cookie", "PHPSESSID=" + bean2.getRetval().getSessionid()); 
						postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
						
						HttpResponse response = httpClient.execute(postMethod); //执行POST方法
						DebugLog.i("resCode = " + response.getStatusLine().getStatusCode());
						
						if(response.getStatusLine().getStatusCode() != 200){
							
							Message obtain = Message.obtain();
							obtain.what = FAILED;
							handler.sendMessage(obtain);
							return;
						}
						parser(EntityUtils.toString(response.getEntity(), "utf-8"));
						
						
					} catch (Exception e) {
						e.printStackTrace();
					} 
				};
			}.start();
		

	}

	protected void parser(String result) {
		DebugLog.i(result);
		Gson gson = new Gson();
		UserInfoBean bean = gson.fromJson(result, UserInfoBean.class);
		email = bean.retval.user_info.em;
		birth_y = bean.retval.user_info.birth_y;
		birth_m = bean.retval.user_info.birth_m;
		qq = bean.retval.user_info.qq;
		sex = bean.retval.user_info.gender;
		zoneid = bean.retval.user_info.zoneid;
		cityid = bean.retval.user_info.city;
		provinceid = bean.retval.user_info.provinceid;
		serv_zone = bean.retval.user_info.serv_zone;
		oldpic = bean.retval.user_info.oldpic;
		picUrl = bean.retval.user_info.picUrl;
		Message obtain = Message.obtain();
    	obtain.what = SUCCESS;
    	handler.sendMessage(obtain);
		
	}

	private void initData()
	{
		getUserInfo();
	}

	private void getUserInfo()
	{
		LoginSQLiteOperator oper = new LoginSQLiteOperator(this);
		LoginBean loginBean = oper.query();
		String name = "";
		if(!TextUtils.isEmpty(loginBean.getRetval().getAgentName())){
			name = loginBean.getRetval().getAgentName();
		}
		if(!TextUtils.isEmpty(loginBean.getRetval().getUserName())){
			name = loginBean.getRetval().getUserName();
		}
		tv_user_info_edit_nicheng_real.setText(name);
	}



	private void initView() {
		setContentView(R.layout.activity_user_info_edit);
		ViewUtils.inject(this);
		showBackButton(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		showTitle("个人信息");
		showHeadRightButton("编辑", new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(UserInfoDetailActivity.this,EditUserInfoActivity.class);
				intent.putExtra("email", email);
				intent.putExtra("birth_y", birth_y);
				intent.putExtra("birth_m", birth_m);
				intent.putExtra("qq", qq);
				intent.putExtra("sex", sex);
				intent.putExtra("zoneid", zoneid);
				intent.putExtra("city", cityid);
				intent.putExtra("provinceid", provinceid);
				intent.putExtra("serv_zone", serv_zone);
				intent.putExtra("oldpic", oldpic);
				intent.putExtra("picUrl", picUrl);
				startActivity(intent);
			}
		});
	}

	
	public void changePassword(View view){
		AlertDialog.Builder builer = new AlertDialog.Builder(this);
		builer.setTitle("修改密码");
		View inflate = View.inflate(this, R.layout.layout_change_password, null);
		et_old_password = (EditText) inflate.findViewById(R.id.et_old_password);
		et_new_password = (EditText) inflate.findViewById(R.id.et_new_password);
		et_new2_password = (EditText) inflate.findViewById(R.id.et_new2_password);
		builer.setView(inflate);
		builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String old = et_old_password.getText().toString();
				String np = et_new_password.getText().toString();
				String rp = et_new2_password.getText().toString();
				if(!np.equals(rp)){
					ToastHelper.ShowToast("两次输入新密码不正确，请重新输入", UserInfoDetailActivity.this);
					return;
				}
				submitPassword(old,np,rp);
			}
		});
		builer.setNegativeButton("取消",new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		builer.show();
	}

	protected void submitPassword(final String opw,final String npw,final String rpw) {
		showLoading();
		LoginSQLiteOperator oper = new LoginSQLiteOperator(this);
		final List<String> querySessionId = oper.queryUserSessionId();
		DebugLog.i(querySessionId.get(0)+" "+querySessionId.get(1)+" "+querySessionId.get(2)+" "+querySessionId.get(3));
		if(querySessionId.size() != 4){
			return;
		}
			//user
			new Thread(){
				public void run() {
					HttpClient httpClient = new DefaultHttpClient();
					try {
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("UserId",querySessionId.get(0)));
						params.add(new BasicNameValuePair("odlp",opw));
						params.add(new BasicNameValuePair("password",npw));
						params.add(new BasicNameValuePair("rep",rpw));
						
					    HttpPost postMethod = new HttpPost(Constants.URL.CHANGEUSERPASSWORD);
					    postMethod.setHeader("Cookie", "PHPSESSID=" + querySessionId.get(2)); 
					    postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
									
					    HttpResponse response = httpClient.execute(postMethod); //执行POST方法
					    DebugLog.i("resCode = " + response.getStatusLine().getStatusCode());
					    
					    if(response.getStatusLine().getStatusCode() != 200){
					    	
					    	Message obtain = Message.obtain();
					    	obtain.what = FAILED;
					    	handler.sendMessage(obtain);
					    	return;
					    }
					    passwordParser(EntityUtils.toString(response.getEntity(), "utf-8"));
					    
									
					} catch (Exception e) {
					    e.printStackTrace();
					} 
				};
			}.start();
	}

	protected void passwordParser(String result) {
		DebugLog.i(result);
		Gson gson = new Gson();
		PasswordBean passwordBean = gson.fromJson(result, PasswordBean.class);
		Message obtain = Message.obtain();
    	obtain.what = SUCCESS_CHANGEPASSWORD;
    	obtain.obj = passwordBean;
    	handler.sendMessage(obtain);
		
	}



	public void exit(View view){
		LoginSQLiteOperator oper = new LoginSQLiteOperator(this);
		oper.delete();
		finish();
	}
	@Override
	protected void onResume() {
		super.onResume();
		if(!isFirstLoad)
			init();
	}
}
